package com.yanqu.road.server.manger.activity.strongholdwar;

import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorConfig;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdDonateConfig;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdTimeConfig;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdTradeConfig;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdWildConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.activity.stronghold.eStrongholdParamType;
import com.yanqu.road.entity.enums.activity.stronghold.eStrongholdTimeType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.bussiness.activity.StrongholdActivityBusiness;
import com.yanqu.road.logic.bussiness.player.activity.UserStrongholdBusiness;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.activity.StrongholdActivityProto;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.strongholdwar.StrongholdActivityModule;
import com.yanqu.road.server.gameplayer.module.activity.strongholdwar.StrongholdModule;
import com.yanqu.road.server.logic.activity.stronghold.StrongholdActivityData;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.DigMgr;
import com.yanqu.road.server.manger.config.GoodsBagMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.pb.StrongholdActivityPb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class StrongholdActivityMgr extends TempMgr {

    public static final int CONDITION_TYPE_WILD_USER = 87;
    public static final int CONDITION_TYPE_WILD_UNION = 88;
    public static final int CONDITION_TYPE_ELIMINATE_USER = 89;
    public static final int CONDITION_TYPE_ELIMINATE_UNION = 90;
    public static final int CONDITION_TYPE_SILVER_UNION = 95;
    private static ActivityInfo activityInfo;
    private static Map<Integer, List<ActivityConditionInfo>> conditionInfoMap = new ConcurrentHashMap<>();
    private static Map<Integer, MallInfo> mallInfoMap = new ConcurrentHashMap<>();
    private static Map<Integer, HuaShiGangFloorConfig> desertConfigMap = new ConcurrentHashMap<>();
    private static Map<Integer, StrongholdTimeConfig> timeConfigMap = new ConcurrentHashMap<>();
    private static Map<Integer, StrongholdWildConfig> wildConfigMap = new ConcurrentHashMap<>();
    private static Map<Integer, StrongholdDonateConfig> donateConfigMap = new ConcurrentHashMap<>();
    private static Map<Integer, StrongholdTradeConfig> tradeConfigMap = new ConcurrentHashMap<>();
    private static Map<String, String> paramConfigMap = new ConcurrentHashMap<>();
    private static List<List<Property>> desertRewardList = new ArrayList<>();

    private static Map<Integer, Map<Long, Map<Integer, List<UserActivityConditionData>>>> userConditionDataMap = new ConcurrentHashMap<>();

    public static Map<Integer, List<ActivityConditionInfo>> getConditionInfoMap() {
        return conditionInfoMap;
    }

    public static Map<Integer, MallInfo> getMallInfoMap() {
        return mallInfoMap;
    }

    public static Map<Integer, HuaShiGangFloorConfig> getDesertConfigMap() {
        return desertConfigMap;
    }

    public static Map<Integer, StrongholdTimeConfig> getTimeConfigMap() {
        return timeConfigMap;
    }

    public static Map<Integer, StrongholdWildConfig> getWildConfigMap() {
        return wildConfigMap;
    }

    public static Map<Integer, StrongholdDonateConfig> getDonateConfigMap() {
        return donateConfigMap;
    }

    public static Map<Integer, StrongholdTradeConfig> getTradeConfigMap() {
        return tradeConfigMap;
    }

    public static Map<String, String> getParamConfigMap() {
        return paramConfigMap;
    }

    public static void reloadActivityData(Map<Integer, ActivityInfo> strongholdActivityInfoMap, Map<Integer, Map<Integer, MallInfo>> activityMallInfoMap, Map<Integer, Map<Integer, List<ActivityConditionInfo>>> activityConditionInfoMap) {
        getLogger().info("reload StrongholdMammonHelp start");
        ActivityInfo inTimeActivity = null;
        for (ActivityInfo activityInfo : strongholdActivityInfoMap.values()) {
            if (ActivityMgr.activityInShowTime(activityInfo)) {
                inTimeActivity = activityInfo;
                break;
            }
        }
        if (inTimeActivity != null) {
            int activityId = inTimeActivity.getActivityId();

            Map<Integer, HuaShiGangFloorConfig> tempDesertConfigMap = StrongholdActivityBusiness.getStrongholdDesertConfig(activityId);
            Map<Integer, StrongholdTimeConfig> tempTimeConfigMap = StrongholdActivityBusiness.getStrongholdTimeConfig(activityId);
            Map<Integer, StrongholdWildConfig> tempWildConfigMap = StrongholdActivityBusiness.getStrongholdWildConfig(activityId);
            Map<Integer, StrongholdDonateConfig> tempDonateConfigMap = StrongholdActivityBusiness.getStrongholdDonateConfig(activityId);
            Map<Integer, StrongholdTradeConfig> tempTradeConfigMap = StrongholdActivityBusiness.getStrongholdTradeConfig(activityId);
            Map<String, String> tempPramConfigMap = StrongholdActivityBusiness.getStrongholdParamConfigMap(activityId);


            mallInfoMap = activityMallInfoMap.get(activityId);
            conditionInfoMap = activityConditionInfoMap.get(activityId);
            desertConfigMap = tempDesertConfigMap;
            timeConfigMap = tempTimeConfigMap;
            wildConfigMap = tempWildConfigMap;
            donateConfigMap = tempDonateConfigMap;
            tradeConfigMap = tempTradeConfigMap;
            paramConfigMap = tempPramConfigMap;
            if (tempPramConfigMap.containsKey("HUASHIGUANG_DIG_PASS_BOX_CONTENT")) {
                desertRewardList = PropertyHelper.parseNewStringToPropertyList(tempPramConfigMap.get("HUASHIGUANG_DIG_PASS_BOX_CONTENT"));
            } else {
                desertRewardList = new ArrayList<>();
            }

            DigMgr.loadActivityConfig(activityId);
        }
        ActivityInfo oldActivityInfo = activityInfo;
        activityInfo = inTimeActivity;


        StrongholdActivityRankMgr.reloadRank();
        if (activityInfo != null) {
            if (oldActivityInfo == null || (oldActivityInfo.getActivityId() != activityInfo.getActivityId())) {
                synchronized (userConditionDataMap) {
                    if(!userConditionDataMap.containsKey(activityInfo.getActivityId())) {
                        userConditionDataMap.put(activityInfo.getActivityId(), UserStrongholdBusiness.getAllUserActivityConditionDataMap(activityInfo.getActivityId()));
                    }
                }
            }
        }
        playerReloadActivity();
//        reloadCross(activityInfo);
        getLogger().info("reload StrongholdMammonHelp finish");
    }

    //添加新的活动条件
    public static void addUserActivityConditionData(long userId, UserActivityConditionData userConditionData) {
        int activityId = userConditionData.getActivityId();
        synchronized (userConditionDataMap) {
            if (!userConditionDataMap.containsKey(activityId)) {
                userConditionDataMap.put(activityId, new ConcurrentHashMap<>());
            }
            if (!userConditionDataMap.get(activityId).containsKey(userId)) {
                userConditionDataMap.get(activityId).put(userId, new ConcurrentHashMap<>());
            }
            if (!userConditionDataMap.get(activityId).get(userId).containsKey(userConditionData.getType())) {
                userConditionDataMap.get(activityId).get(userId).put(userConditionData.getType(), new ArrayList<>());
            }
            userConditionDataMap.get(activityId).get(userId).get(userConditionData.getType()).add(userConditionData);
        }
    }

    //返回用户的condition
    public static Map<Integer, List<UserActivityConditionData>> getUserActivityConditionDataMap(long userId, int activityId) {
        if (userConditionDataMap.containsKey(activityId)) {
            if (userConditionDataMap.get(activityId).containsKey(userId)) {
                return userConditionDataMap.get(activityId).get(userId);
            }
        }
        return null;
    }

    @Deprecated
    private static void reloadCross(ActivityInfo activityInfo) {
        if (activityInfo != null) {
            StrongholdWarProto.CrossStrongholdReloadReqMsg.Builder req = StrongholdWarProto.CrossStrongholdReloadReqMsg.newBuilder();
            req.setActivityId(activityInfo.getActivityId());
            YanQuMessage msg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_STRONGHOLD_RELOAD_ACTIVITY_INFO, req);
            GamePlayerMgr.sendPacket(0, msg);
        }

    }

    private static void playerReloadActivity() {
        List<GamePlayer> playerList = GamePlayerMgr.getCopyPlayerList();
        playerList.forEach(player -> {
            player.getModule(StrongholdActivityModule.class).addNewActivity();
            player.getModule(StrongholdActivityModule.class).syncActivity();
            player.getModule(StrongholdModule.class).loginSendMsg();
            player.getModule(StrongholdModule.class).afterLogin();
        });
    }

    public static ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public static StrongholdTimeConfig getStrongholdWildTimeConfig() {
        for (StrongholdTimeConfig config : timeConfigMap.values()) {
            if (config.getType() == eStrongholdTimeType.WILD.getValue()) {
                return config;
            }
        }
        return null;
    }

    /**
     * 是否休息期
     */
    public static boolean isRestTime() {
        return isInSpecialTime(eStrongholdTimeType.REST);
    }

    private static boolean isInSpecialTime(eStrongholdTimeType strongholdTimeType) {
        List<StrongholdTimeConfig> configList = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : configList) {
            if (config.getType() == strongholdTimeType.getValue()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否野外据点期
     *
     * @return
     */
    public static boolean isWildTime() {
        return isInSpecialTime(eStrongholdTimeType.WILD);
    }

    /**
     * 是否备战期
     *
     * @return
     */
    public static boolean isPrepareTime() {
        return isInSpecialTime(eStrongholdTimeType.PREPARE);
    }

    public static boolean isRewardTime() {
        return isInSpecialTime(eStrongholdTimeType.REWARD);
    }

    /**
     * 是否淘汰赛期间
     *
     * @return
     */
    public static boolean isEliminateTime() {
        return isInSpecialTime(eStrongholdTimeType.ELIMINATE);
    }

    /**
     * 据点战当前时间阶段配置列表
     * 同一时刻 可能存在多个阶段
     *
     * @return
     */
    public static List<StrongholdTimeConfig> getStrongholdTimeConfig() {
        List<StrongholdTimeConfig> configList = new ArrayList<>();
        if (activityInfo == null) {
            return configList;
        }
        long hours = getHours();
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getBeginTime() <= hours && timeConfig.getEndTime() > hours) {
                configList.add(timeConfig);
            }
        }
        return configList;
    }

    /**
     * 活动开始到现在的小时数
     *
     * @return
     */
    public static long getHours() {
        long beginTime = activityInfo.getBeginTime();
        return (System.currentTimeMillis() / 1000 - beginTime) / 3600;
    }

    /**
     * 是否可以捐献银两
     *
     * @return
     */
    public static boolean isDonateSliverTime() {
        StrongholdTimeConfig config = getFirstRoundEliminateTimeConfig();
        if (config == null) {
            return false;
        }
        int beginTime = config.getBeginTime();
        long limitDonateTime = activityInfo.getBeginTime() + beginTime * 3600 - dealNeedTime();
        if (System.currentTimeMillis() / 1000 < limitDonateTime) {
            //第一轮淘汰赛5分钟前可以捐献
            return true;
        }
        return false;
    }

    private static StrongholdTimeConfig getFirstRoundEliminateTimeConfig() {
        StrongholdTimeConfig config = null;
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getType() == eStrongholdTimeType.ELIMINATE.getValue()) {
                //如果是淘汰赛，比较开始时间，取最小的，第一轮淘汰赛
                if (config == null || timeConfig.getBeginTime() < config.getBeginTime()) {
                    config = timeConfig;
                }
            }
        }
        return config;
    }

    /**
     * 是否可以捐献道具
     * 淘汰赛前 5分钟 到淘汰赛结束都不允许捐赠。  淘汰赛最后一轮结束后也不允许捐赠
     *
     * @return
     */
    public static boolean isDonateItemTime() {
        if (isWildTime()) {
            return true;
        }
        if (isEliminateTime()) {
            return false;
        }
        if (isRestTime()) {
            List<StrongholdTimeConfig> configList = getStrongholdTimeConfig();
            for (StrongholdTimeConfig config : configList) {
                if (config.getType() == eStrongholdTimeType.REST.getValue()) {
                    long beginTime = activityInfo.getBeginTime();
                    int endTime = config.getEndTime();
                    long now = System.currentTimeMillis() / 1000;
                    if (now > beginTime + config.getBeginTime() * 3600 && now + dealNeedTime() < beginTime + endTime * 3600) {
                        // 如果当前时间 > 休息期的开始时间 且 是休息期结束时间的前5分钟， 则可以捐献
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private static int dealNeedTime() {
        return 5 * 60;
    }


    public static int getCurBaseLv(int curLv, List<Integer> curProcess) {
        int lv = curLv;
        while (nextLv(lv, curProcess)) {
            lv++;
        }
        return lv;
    }

    private static boolean nextLv(int curLv, List<Integer> curProcess) {
        StrongholdDonateConfig nextConfig = donateConfigMap.get(curLv + 1);
        if (nextConfig == null) {
            return false;
        }
        StrongholdDonateConfig config = donateConfigMap.get(curLv);
        if (config == null) {
            return false;
        }
        String needProcess = config.getNeedProcess();
        String[] arr = needProcess.split("\\|");
        for (int i = 0; i < arr.length; i++) {
            int needValue = Integer.parseInt(arr[i]);
            Integer curValue = curProcess.get(i);
            if (curValue < needValue) {
                return false;
            }
        }
        return true;
    }

    /**
     * 是否上传野外据点排名时间
     *
     * @return
     */
    public static boolean isUploadWildRankTime() {
        if (activityInfo == null) {
            return false;
        }
        long hours = getHours();
        StrongholdTimeConfig curTimeConfig = null;
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getBeginTime() <= hours && timeConfig.getEndTime() > hours && timeConfig.getType() == eStrongholdTimeType.REST.getValue()) {
                curTimeConfig = timeConfig;
                break;
            }
        }
        if (curTimeConfig == null) {
            return false;
        }
        StrongholdTimeConfig preConfig = timeConfigMap.get(curTimeConfig.getTimeId() - 1);
        if (preConfig == null) {
            return false;
        }
        if (preConfig.getType() != eStrongholdTimeType.WILD.getValue()) {
            return false;
        }
        long preEndTime = activityInfo.getBeginTime() + preConfig.getEndTime() * 3600;
        if (System.currentTimeMillis() / 1000 < preEndTime + 180) {
            return false;
        }
        return true;
    }

    /***
     * 淘汰赛当前轮数
     * @return
     */
    public static int getCurEmilinateRound() {
        long hours = getHours();
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getBeginTime() <= hours && timeConfig.getEndTime() > hours) {
                if (timeConfig.getType() == eStrongholdTimeType.ELIMINATE.getValue()) {
                    return timeConfig.getTimeId();

                } else if (timeConfig.getType() == eStrongholdTimeType.REST.getValue()) {
                    return timeConfig.getTimeId() + 1;
                }
            }
        }
        return 0;
    }

    public static boolean isUploadEliminateTime() {
        if (activityInfo == null) {
            return false;
        }
        long hours = getHours();
        StrongholdTimeConfig curTimeConfig = null;
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getBeginTime() <= hours && timeConfig.getEndTime() > hours && timeConfig.getType() == eStrongholdTimeType.REST.getValue()) {
                curTimeConfig = timeConfig;
                break;
            }
        }
        if (curTimeConfig == null) {
            return false;
        }
        StrongholdTimeConfig preConfig = timeConfigMap.get(curTimeConfig.getTimeId() - 1);
        if (preConfig == null) {
            return false;
        }
        if (preConfig.getType() != eStrongholdTimeType.ELIMINATE.getValue()) {
            return false;
        }
        long preEndTime = activityInfo.getBeginTime() + preConfig.getEndTime() * 3600;
        if (System.currentTimeMillis() / 1000 < preEndTime + 180) {
            return false;
        }
        return true;
    }

    public static boolean isDispatchEliminatePatronsTime() {
        if (!isRestTime()) {
            return false;
        }
        List<StrongholdTimeConfig> configList = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : configList) {
            if (config.getType() == eStrongholdTimeType.REST.getValue()) {
                long beginTime = activityInfo.getBeginTime();
                int endTime = config.getEndTime();
                long now = System.currentTimeMillis() / 1000;
                if (now > beginTime + config.getBeginTime() * 3600 && now + dealNeedTime() < beginTime + endTime * 3600) {
                    // 如果当前时间 > 休息期的开始时间 且 是休息期结束时间的前5分钟， 则可以派遣
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 是查看野外排行榜吗
     *
     * @return
     */
    public static boolean isLookWildRank() {
        long beginTime = activityInfo.getBeginTime();
        StrongholdTimeConfig timeConfig = getFirstRoundEliminateTimeConfig();
        //第一轮淘汰赛结束时间
        long endTime = beginTime + timeConfig.getEndTime() * 3600;
        return System.currentTimeMillis() < endTime * 1000;
    }

    /**
     * 是查看淘汰赛排行榜吗
     *
     * @return
     */
    public static boolean isLookEliminateRank() {
        return false;
    }


    public static int getQualifyNum() {
        if (activityInfo == null) {
            return 0;
        }
        long hours = getHours();
        int timeId = 0;
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getBeginTime() <= hours && timeConfig.getEndTime() > hours) {
                if (timeConfig.getType() == eStrongholdTimeType.REST.getValue()) {
                    timeId = timeConfig.getTimeId() - 1;
                } else if (timeConfig.getType() == eStrongholdTimeType.ELIMINATE.getValue()) {
                    timeId = timeConfig.getTimeId() - 2;
                }
                break;
            }
        }
        if (timeId == 0) {
            return 0;
        }
        return Integer.parseInt(timeConfigMap.get(timeId).getParam());
    }

    public static BigInteger calcBlood(BigInteger ability) {
        String param = paramConfigMap.get("union_blood_param");
        String[] arr = param.split("\\|");
        Map<Integer, Integer> abilityEnlargeMap = new HashMap<>();
        for (String s : arr) {
            String[] split = s.split(";");
            if (split.length >= 2) {
                int key = Integer.parseInt(split[0]);
                int value = Integer.parseInt(split[1]);
                abilityEnlargeMap.put(key, value);
            } else if (split.length == 1) {
                //默认乘以1000
                abilityEnlargeMap.put(0, Integer.parseInt(split[0]) * 1000);
            }
        }
        int openDays = getOpenDays();
        int day = Integer.MAX_VALUE;
        int enlargeValue = 1;
        int maxDays = 0;
        for (Map.Entry<Integer, Integer> entry : abilityEnlargeMap.entrySet()) {
            Integer days = entry.getKey();
            if (days >= maxDays) {
                maxDays = days;
            }
            if (openDays < days && days < day) {
                //如果当前天数大于配置
                enlargeValue = entry.getValue();
                day = days;
            }
        }
        if (openDays >= maxDays) {
            enlargeValue =  abilityEnlargeMap.get(maxDays);
        }
       return new BigDecimal(ability).multiply(new BigDecimal(enlargeValue)).divide(new BigDecimal(1000), BigDecimal.ROUND_UP).toBigInteger();
    }

    private static int getOpenDays() {
        //秒级
        long beginShowTime = activityInfo.getBeginShowTime();
        List<Long> serverIdList = activityInfo.getServerIdList();
        //秒级
        long minOpenTime = 0;
        for (Long serverId : serverIdList) {
            ServerInfo serverInfo = ServerListMgr.getServerInfo(serverId);
            if (serverInfo != null) {
                if (minOpenTime == 0) {
                    minOpenTime = serverInfo.getOpenTime();
                } else if (minOpenTime > serverInfo.getOpenTime()) {
                    minOpenTime = serverInfo.getOpenTime();
                }
            }
        }
        long days = (beginShowTime - minOpenTime) / 3600 / 24;
        return (int) days + 1;
    }

    public static int getHpAddByRank(int rank) {
        if (rank <= 0) {
            return 0;
        }
        String rankAdditionParam = paramConfigMap.get("union_blood_rank_addition");
        String[] arr = rankAdditionParam.split(";");
        if (rank > arr.length) {
            return 0;
        }
        return Integer.parseInt(arr[rank - 1]);
    }

    public static int getUnionBaseAdd(int lv) {
        StrongholdDonateConfig config = donateConfigMap.get(lv);
        if (config != null) {
            return config.getHpAdd();
        }
        return 0;
    }

    public static ActivityInfo getOpenActivityInfo() {
        if (ActivityMgr.activityInShowTime(activityInfo)) {
            return activityInfo;
        }
        return null;
    }

    public static int getMaxRankByType(int activityId, int conditionType) {
        int maxRank = 0;
        List<ActivityConditionInfo> dataList = getActivityConditionInfoList(activityId, conditionType);
        if (null != dataList) {
            for (ActivityConditionInfo conditionInfo : dataList) {
                if (conditionInfo.getParamList().get(1).intValue() > maxRank) {
                    maxRank = conditionInfo.getParamList().get(1).intValue();
                }
            }
        }
        return maxRank;
    }

    public static List<ActivityConditionInfo> getActivityConditionInfoList(int activityId, int type) {
        ActivityInfo activityInfo = getOpenActivityInfo(activityId);
        if (null != activityInfo) {
            return conditionInfoMap.get(type);
        }
        return null;
    }

    public static ActivityInfo getOpenActivityInfo(int activityId) {
        if (ActivityMgr.activityInShowTime(activityInfo) && activityInfo.getActivityId() == activityId) {
            return activityInfo;
        }
        return null;
    }

    public static List<Integer> getUnionConditionTypeList() {
        List<Integer> list = new ArrayList<>();
        list.add(eGamePlayerEventType.StrongholdWildUnionScoreRank.getValue());
        list.add(eGamePlayerEventType.StrongholdEliminateUnionRank.getValue());
        list.add(eGamePlayerEventType.StrongholdDonateSilverRank.getValue());
        return list;
    }

    public static List<Integer> getUserConditionTypeList() {
        List<Integer> list = new ArrayList<>();
        list.add(eGamePlayerEventType.StrongholdWildScoreRank.getValue());
        list.add(eGamePlayerEventType.StrongholdEliminateRank.getValue());
        return list;
    }

    public static ActivityInfo getInTimeActivityInfo(int activityId) {
        if (ActivityMgr.activityInTime(activityInfo) && activityInfo.getActivityId() == activityId) {
            return activityInfo;
        }
        return null;
    }


    public static Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfoMap(int activityId) {
        ActivityInfo inTimeActivityInfo = getOpenActivityInfo(activityId);
        if (null != inTimeActivityInfo) {
            return conditionInfoMap;
        }
        return null;
    }

    public static ActivityConditionInfo getActivityConditionInfo(int activityId, int conditionId) {
        for (List<ActivityConditionInfo> conditionInfoList : conditionInfoMap.values()) {
            for (ActivityConditionInfo conditionInfo : conditionInfoList) {
                if (conditionId == conditionInfo.getConditionId()) {
                    return conditionInfo;
                }
            }
        }
        return null;
    }

    public static ActivityConditionInfo getActivityConditionInfoByRank(int activityId, int type, int myRank) {
        List<ActivityConditionInfo> dataList = getActivityConditionInfoList(activityId, type);
        if (null != dataList) {
            for (ActivityConditionInfo conditionInfo : dataList) {
                if (myRank >= conditionInfo.getParamList().get(0).intValue() && myRank <= conditionInfo.getParamList().get(1).intValue()) {
                    return conditionInfo;
                }
            }
        }
        return null;
    }

    public static int getCommonItemId() {
        String s = paramConfigMap.get(eStrongholdParamType.WILD_ITEM_ID_PARAM.getKey());
        return Integer.parseInt(s.split(";")[3]);
    }

    public static int getDonateItemIdByType(int type) {
        String s = paramConfigMap.get(eStrongholdParamType.WILD_ITEM_ID_PARAM.getKey());
        return Integer.parseInt(s.split(";")[type]);
    }

    public static Property getMammonUseReward(int goodsId) {
        int boxId = 0;
        try {
            GoodsInfo goodsInfo = CommonMgr.getGoodsInfo(goodsId);
            if (goodsInfo != null) {
                boxId = goodsInfo.getParamList().get(0).intValue();
            }
        } catch (Exception e) {

        }
        OpenGoodsBagResult randomGoods = GoodsBagMgr.getRandomGoods(boxId);
        return randomGoods.getReward();
    }

    public static StrongholdActivityProto.StrongholdActivityDataMsg.Builder getStrongholdActivityDetailMsg(Map<Integer, StrongholdActivityData> dataMap, String language) {
        return StrongholdActivityPb.parseActivityDetailMsg(dataMap);
    }

    public static int getPatronsFreeTimes(GamePlayer player, int patronsId) {
        if (isWildTime()) {
            return getWildFreeTimes();
        } else if (isEliminateTime()) {
            return getEliminateFreeTimes();
        }
        return 0;
    }

    public static int getWildFreeTimes() {
        return Integer.parseInt(paramConfigMap.get(eStrongholdParamType.WILD_PARTONS_FREE_TIMES.getKey()));
    }

    public static int getWildBuyItemTimes() {
        return 1;
    }

    public static String getWildBuyItemConsume() {
        return "";
    }

    public static int getEliminateFreeTimes() {
        return Integer.parseInt(paramConfigMap.get(eStrongholdParamType.WILD_PARTONS_FREE_TIMES.getKey()));
    }

    /**
     * 野外战派遣消耗
     *
     * @param buyTimes
     * @return
     */
    public static String getWildDispatchConsume(int buyTimes) {
        String[] arr = paramConfigMap.get(eStrongholdParamType.WILD_PARTONS_BUY_CONSUME.getKey()).split("\\|");
        return arr[buyTimes];
    }

    /**
     * 据点战最大购买次数
     *
     * @return
     */
    public static int getWildBuyTimes() {
        return paramConfigMap.get(eStrongholdParamType.WILD_PARTONS_BUY_CONSUME.getKey()).split("\\|").length;
    }

    public static boolean isUploadEliminatePatronsTime() {
        long beginTime = activityInfo.getBeginTime();
        List<StrongholdTimeConfig> list = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : list) {
            if (config.getType() == eStrongholdTimeType.REST.getValue()) {
                int endTime = config.getEndTime();
                if (System.currentTimeMillis() / 1000 + dealNeedTime() > beginTime + endTime * 3600) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isEliminateAutoDispatchPatronsTime() {
        long beginTime = activityInfo.getBeginTime();
        List<StrongholdTimeConfig> list = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : list) {
            if (config.getType() == eStrongholdTimeType.REST.getValue()) {
                long endTime = config.getEndTime() * 3600 + beginTime;
                long startTime = config.getBeginTime() * 3600 + beginTime;
                long now = System.currentTimeMillis() / 1000;
                if (now > startTime + 60  &&  now < endTime) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isNeedResetEliminateAutoDispatchPatronsTime() {
        long beginTime = activityInfo.getBeginTime();
        List<StrongholdTimeConfig> list = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : list) {
            if (config.getType() == eStrongholdTimeType.REST.getValue()) {
                long startTime = config.getBeginTime() * 3600 + beginTime;
                long now = System.currentTimeMillis() / 1000;
                if (now > startTime + 60  &&  now < startTime + 120) {
                    return true;
                }
            }
        }
        return false;
    }

    public static String getMammonConsume(int type) {
        return paramConfigMap.get(eStrongholdParamType.MAMMON_HELP_CONSUME.getKey());
    }

    public static Property getEliminateKillReward() {
        int killItemId = Integer.parseInt(paramConfigMap.get("eliminate_kill_reward"));
        OpenGoodsBagResult randomGoods = GoodsBagMgr.getRandomGoods(killItemId);
        return new Property(randomGoods.getReward());
    }

    public static int getPowerItemId() {
        return Integer.parseInt(paramConfigMap.get(eStrongholdParamType.WILD_RECOVER_POWER_ITEM.getKey()));
    }

    public static StrongholdTradeConfig getTradeConfig(int id) {
        return tradeConfigMap.get(id);
    }

    public static boolean activityInRewardPeriod(ActivityInfo openActivityInfo) {
        return isInSpecialTime(eStrongholdTimeType.REWARD);
    }

    public static boolean activityInCanRewardPeriod() {
        if (activityInfo == null) {
            return false;
        }
        long beginTime = activityInfo.getBeginTime();
        for (StrongholdTimeConfig config : timeConfigMap.values()) {
            if (config.getType() == eStrongholdTimeType.REWARD.getValue()) {
                //是领奖期
                long rewardBeginTime = beginTime + config.getBeginTime() * 3600;
                long rewardEndTime = beginTime + config.getBeginTime() * 3600 + config.getDurationTime() * 3600;
                long now = System.currentTimeMillis() / 1000;
                if (now > rewardBeginTime + dealNeedTime() && now < rewardEndTime) {
                    return true;
                }

            }
        }
        return false;
    }

    public static int getDesertPassItem() {
        return Integer.parseInt(paramConfigMap.getOrDefault("desert_pass_item", "0"));
    }

    public static List<List<Property>> getDesertRewardList() {
        return desertRewardList;
    }

    public static Property getEliminateConsume(int buyTimes) {
        int itemId = Integer.parseInt(paramConfigMap.get("eliminate_partons_buy_item_id"));
        String[] arr = paramConfigMap.get("eliminate_partons_buy_item_num").split("\\|");
        if (buyTimes >= 0 && buyTimes < arr.length) {
            return new Property(itemId, new BigInteger(arr[buyTimes]));
        }
        return null;
    }

    public static int getEliminateBuyTimes() {
        return paramConfigMap.get("eliminate_partons_buy_item_num").split("\\|").length;
    }

    public static void conditionNotify(long userId, int event, Object object) {
        GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (gamePlayer != null) {
            gamePlayer.notifyListener(event, object);
        } else {
            if (activityInfo != null) {
                if (event == eGamePlayerEventType.StrongholdWildScoreRank.getValue()) {
                    conditionNotify(activityInfo.getActivityId(), userId, event, object);
                } else if (event == eGamePlayerEventType.StrongholdEliminateRank.getValue()) {
                    conditionNotify(activityInfo.getActivityId(), userId, event, object);
                }
            }
        }
    }

    public static void conditionNotify(Integer activityId, long userId, int event, Object object) {
        GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (gamePlayer != null) {
            gamePlayer.notifyListener(event, object);
        } else {
            UnionRiseRankArgs args = (UnionRiseRankArgs) object;
            if (null != args) {
                synchronized (userConditionDataMap) {
                    List<UserActivityConditionData> tempList = new ArrayList<>();
                    tempList.addAll(userConditionDataMap.get(activityId).get(userId).get(StrongholdActivityMgr.CONDITION_TYPE_WILD_USER));
                    tempList.addAll(userConditionDataMap.get(activityId).get(userId).get(StrongholdActivityMgr.CONDITION_TYPE_WILD_UNION));
                    tempList.addAll(userConditionDataMap.get(activityId).get(userId).get(StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_USER));
                    tempList.addAll(userConditionDataMap.get(activityId).get(userId).get(StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION));
                    for (UserActivityConditionData data : tempList) {
                        if (data.getActivityId() == activityId) {
                            if (data.getType() == StrongholdActivityMgr.CONDITION_TYPE_WILD_UNION || data.getType() == StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_UNION) {
                                data.setValue(data.getValue().add(args.getValue()));
                                if (UnionRiseRankArgs.NOTIFY_TYPE_NORMAL == args.getType() || UnionRiseRankArgs.NOTIFY_TYPE_JOIN == args.getType()) {
                                    data.setUnionUid(args.getUnionUid());
                                } else if (UnionRiseRankArgs.NOTIFY_TYPE_REMOVE == args.getType() || UnionRiseRankArgs.NOTIFY_TYPE_DELETE == args.getType()) {
                                    data.setUnionUid("");
                                }
                                if (data.getType() == StrongholdActivityMgr.CONDITION_TYPE_WILD_UNION) {
                                    StrongholdActivityRankMgr.changeUnionActivityValue(data.getActivityId(), data.getType(), args.getUnionUid(), userId, data, args.getType());
                                } else {
                                    StrongholdActivityRankMgr.changeUnionActivityValueNotUpload(data.getActivityId(), data.getType(), args.getUnionUid(), userId, data, args.getType());
                                }
                                if (UnionRiseRankArgs.NOTIFY_TYPE_DELETE == args.getType()) {//解散商会
//                                    StrongholdActivityRankMgr.removeUnionActivityRank(data.getActivityId(), data.getType(), args.getUnionUid());
                                }
                            } else if (data.getType() == StrongholdActivityMgr.CONDITION_TYPE_WILD_USER || data.getType() == StrongholdActivityMgr.CONDITION_TYPE_ELIMINATE_USER) {
                                data.setValue(data.getValue().add(args.getValue()));
                                if (data.getValue().compareTo(BigInteger.ZERO) > 0) {
                                    StrongholdActivityRankMgr.changeRank(activityId, data.getType(), UserMgr.getUserInfo(userId), data.getValue());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 是否已经进入领奖期
     *
     * @return
     */
    public static boolean isGameFinish() {
        if (activityInfo == null) {
            return true;
        }
        if (timeConfigMap == null) {
            return true;
        }
        StrongholdTimeConfig rewardTimeConfig = null;
        for (StrongholdTimeConfig config : timeConfigMap.values()) {
            if (config.getType() == eStrongholdTimeType.REWARD.getValue()) {
                rewardTimeConfig = config;
                break;
            }
        }
        if (rewardTimeConfig == null) {
            return true;
        }
        long rewardBeginTime = activityInfo.getBeginTime() + rewardTimeConfig.getBeginTime() * 3600;
        if (System.currentTimeMillis() > rewardBeginTime * 1000) {
            return true;
        }
        return false;
    }

    public static int getTimeId() {
        List<StrongholdTimeConfig> configList = getStrongholdTimeConfig();
        for (StrongholdTimeConfig config : configList) {
            if (config.getType() <= eStrongholdTimeType.ELIMINATE.getValue()) {
                return config.getTimeId();
            }
        }
        return 0;
    }

    /**
     * 野外资源积分id
     *
     * @return
     */
    public static int getWildIntegarlId() {
        try {
            String param = paramConfigMap.get("wild_integral_item");
            if (param == null) {
                return 0;
            }
            return Integer.parseInt(param);
        } catch (Exception e) {
            getLogger().error("wild_integral_item error. {}", paramConfigMap.get("wild_integral_item"), e);
        }
        return 0;
    }

    /**
     * 淘汰赛每次出战获得的奖励
     *
     * @param buyTimes
     * @return
     */
    public static Property getEliminateChallengeReward(int buyTimes) {
        int shovelItemId = Integer.parseInt(paramConfigMap.get("desert_shovel_item_id"));
        int shovelNum = 1 + Integer.parseInt(paramConfigMap.get("reward_shovel_num")) * buyTimes;
        return new Property(shovelItemId, BigInteger.valueOf(shovelNum));
    }

    /**
     * 财神助力生效类型
     *
     * @return
     */
    public static int getMammonHelpEffectType() {
        return Integer.parseInt(paramConfigMap.get("mammon_help_effect_type"));
    }

    /**
     * 西域通商结束时间 单位ms
     *
     * @return
     */
    public static long getTradeReturnTime() {
        long beginTime = activityInfo.getBeginTime();
        for (StrongholdTimeConfig config : timeConfigMap.values()) {
            if (config.getType() == eStrongholdTimeType.TRADE_RETURN.getValue()) {
                return (beginTime + config.getEndTime() * 3600) * 1000;
            }
        }
        return System.currentTimeMillis() + 24 * 3600 * 1000;
    }

    /**
     * 获取移动消耗体力 默认1点
     *
     * @return
     */
    public static int getMovePower() {
        try {
            String s = paramConfigMap.get(eStrongholdParamType.WILD_MOVE_POWER.getKey());
            return Integer.parseInt(s);
        } catch (Exception e) {
            getLogger().error("WILD_MOVE_POWER PARAM {} error.", paramConfigMap.get(eStrongholdParamType.WILD_MOVE_POWER.getKey()), e);
        }
        return 2;
    }

    /**
     * 获取搜索消耗体力 默认1点
     *
     * @return
     */
    public static int getSearchPower() {
        try {
            String s = paramConfigMap.get(eStrongholdParamType.WILD_SEARCH_POWER.getKey());
            return Integer.parseInt(s);
        } catch (Exception e) {
            getLogger().error("WILD_SEARCH_POWER PARAM {} error.", paramConfigMap.get(eStrongholdParamType.WILD_SEARCH_POWER.getKey()), e);
        }
        return 1;
    }

    /**
     * 野外据点体力上限
     *
     * @return
     */
    public static int getWildMaxPower() {
        try {
            return Integer.parseInt(paramConfigMap.get("wild_power_param").split(";")[1]);
        } catch (Exception e) {

        }
        return 30;
    }

    /**
     * 野外据点初始化体力
     *
     * @return
     */
    public static int getWildInitPower() {
        try {
            return Integer.parseInt(paramConfigMap.get("wild_power_param").split(";")[0]);
        } catch (Exception e) {

        }
        return 30;
    }

    /**
     * 获取体力恢复时间间隔，单位 s
     *
     * @return
     */
    public static long getWildPowerRecoverTime() {
        try {
            return Integer.parseInt(paramConfigMap.get("wild_power_recover_time"));
        } catch (Exception e) {

        }
        return 300;
    }

    public static boolean isAfterWildTime() {
        if (null == activityInfo) {
            return false;
        }
        long beginTime = activityInfo.getBeginTime();
        for (StrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            if (timeConfig.getType() == eStrongholdTimeType.WILD.getValue()) {
                long wildEndTime = (beginTime + timeConfig.getEndTime() * 3600) * 1000;
                return System.currentTimeMillis() > wildEndTime;
            }
        }
        return true;
    }


    @Override
    public boolean init() throws Exception {
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean save() {
        for (Map<Long, Map<Integer, List<UserActivityConditionData>>> allUserDataMap : userConditionDataMap.values()) {
            for (Map<Integer, List<UserActivityConditionData>> userDataMap : allUserDataMap.values()) {
                for (List<UserActivityConditionData> conditionList : userDataMap.values()) {
                    List<UserActivityConditionData> tempList = new ArrayList<>(conditionList);
                    for (UserActivityConditionData condition : tempList) {
                        if (condition.getOp() == DataStatus.Insert) {
                            UserStrongholdBusiness.addUserActivityConditionData(condition);
                        } else if (condition.getOp() == DataStatus.Update) {
                            UserStrongholdBusiness.updateUserActivityConditionData(condition);
                        }
                    }
                }
            }
        }
        return true;
    }
}

